package com.northwest_man.refactor_tool;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


// 计算类的import数量
public class CountImport {
    private static final String[] curProjectPkg = new String[]{};
    // import\s+com\.interfocusllc\.patpat\.[^;]+;
    private static final String[] regex = new String[]{"import\\s+com\\.interfocusllc\\.patpat\\.[^;]+;",
            "import android\\.[^;]+;"};

    public static void main() {
        final List<Relationship> resultList = new ArrayList<>();
        final File folder = new File(Constants.pastedParentFolder);
        count(folder, resultList);
        resultList.sort(Comparator.comparingInt(o -> o.importCount));
        for (final Relationship item : resultList) {
            if (item.importCount > 1) {
                new File(item.fileName).delete();
                System.out.printf("%-4d: %100s\n", item.importCount, item.fileName);
            }
        }
    }

    private static void count(final File folder, final List<Relationship> resultList) {
        if (folder.isDirectory()) {
            final File[] files = folder.listFiles();
            for (final File file : files) {
                if (file.isDirectory()) {
                    count(file, resultList);
                } else {
                    doFile(file, resultList);

                }
            }
        } else {
            doFile(folder, resultList);
        }
    }

    private static void doFile(final File file, final List<Relationship> resultList) {
        if (file.isDirectory()) return;
        final StringBuilder fileContent = FileUtil.getFileContent(file);
        int i = 0;
        for (final String regexItem : regex) {
            final Pattern pattern = Pattern.compile(regexItem);
            final Matcher matcher = pattern.matcher(fileContent);

            while (matcher.find()) {
                i++;
            }
        }
        resultList.add(new Relationship(file.getAbsolutePath(), i));
    }

    private static final class Relationship {
        public final String fileName;
        public final int importCount;

        private Relationship(final String fileName, final int importCount) {
            this.fileName = fileName;
            this.importCount = importCount;
        }
    }
}
